<?php
/***********************************
* THIS FILE WILL FIRE FOR EACH FILE
* THAT HAS BEEN UPLOADED
***********************************/

// Include config file
include('./common.php');

if(isset($_POST['actionType'])){
	 
	// Connect to database
	//$link = dbConnect();
	
	// Attempt to auth user with database
	/*
	$user = auth($_POST['username'], $_POST['password']);
	if($user == ""){
		echo "output=loginError";
		return;
	}
	*/

	//if they are logged in handle the stuff
	switch($_POST['actionType']){
		case "add":
			addFile();
		break;
	
		case "remove":
			removeFile();
		break;
		
		default:
			echo "output=invalidAction&action=".$_POST['actionType'];
		break;
	}
}else{
	echo "output=noAction";
}

/***************************************
* Takes an uploaded file from Flash and
* adds it to the server's file system
****************************************/
function addFile(){
	//get the absolute image directory from flash
	$abImgDir = $_POST['abImgDir'];

	if(isset($_FILES['fileFromFlash'])){	
		//define allowed image types
		$IMAGETYPE_GIF = 1;
		$IMAGETYPE_JPEG = 2;
		$IMAGETYPE_PNG = 3;
		
		//hold a var
		$flashFile = $_FILES['fileFromFlash'];
		
		//get the data about the image
		$imageData = getimagesize($flashFile['tmp_name']);
		
		//make a new name and strip out the path if we need to
		//$newImageName = str_replace(" ", "_", basename($flashFile['name']));
		$newImageName = basename($flashFile['name']);
		
		//check the width and height
		if($_POST['maxWidth'] < $imageData[0] || $_POST['maxHeight'] < $imageData[1]){
			echo "output=fileDimensionError&maxWidth=".$_POST['maxWidth']."&maxHeight=".$_POST['maxHeight'];
			return;
		}
		
		//check the type
		if($imageData[2] != $IMAGETYPE_GIF && $imageData[2] != $IMAGETYPE_JPEG && $imageData[2] != $IMAGETYPE_PNG){
			echo "output=fileTypeError&name=".$newImageName;
			return;
		}
		
		//add a little salt to that
		$salt = substr(md5(time()), rand(0, 5), 7);
		
		//start to process the image - format is <salt>-<filename>
		$uploadResult = @move_uploaded_file($flashFile['tmp_name'], $abImgDir.$salt.$_POST['spacer'].$newImageName);
		if($uploadResult){
			echo "output=success&name=".$newImageName."&width=".$imageData[0]."&height=".$imageData[1]."&salt=".$salt;
		}else{
			echo "output=uploadFail&name=".$newImageName;
		}
	}else{
		echo "output=missingFile";
	}
}

/***************************************
* Removes a file that was uploaded
****************************************/
function removeFile(){
	//get the absolute image directory from flash
	
	if(isset($_POST['fileName'])){
		//remove the file from the file system
		if(@unlink($_POST['abImgDir'].$_POST['fileName'])){
			echo "output=success";
		}else{
			echo "output=removeFail";
		}
	}else{
		echo "output=missingFile";
	}
}
?>